package com.example.huadu_server.config;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {
    @Autowired
    private StringRedisTemplate redisTemplate;

    // 保存到 Redis
    public void saveToRedis(String key, Object value, long timeout, TimeUnit timeUnit) {
        redisTemplate.opsForValue().set(key, JSON.toJSONString(value), timeout, timeUnit);
    }

    // 从 Redis 获取
    public <T> T getFromRedis(String key, Class<T> clazz) {
        String json = redisTemplate.opsForValue().get(key);
        return json != null ? JSON.parseObject(json, clazz) : null;
    }

    // 从 Redis 删除
    public void deleteFromRedis(String key) {
        redisTemplate.delete(key);
    }
}
